<template>
    <div class="icon-picker">
        <!-- 搜索框 -->
        <input type="text" v-model="search" placeholder="搜索图标..." class="form-control mb-3" />

        <!-- 加载中 -->
        <div v-if="loading" class="text-center text-muted mb-2">加载中...</div>

        <!-- 加载失败 -->
        <div v-else-if="error" class="text-danger text-center mb-2">
            加载失败，请<a href="#" @click.prevent="fetchData" class="alert-link text-primary">重试</a>
        </div>

        <!-- 无数据 -->
        <div v-else-if="filteredIcons.length === 0" class="text-center text-muted mb-2">暂无可用的图标</div>

        <!-- 图标列表 -->
        <div v-else class="icon-grid">
            <div v-for="icon in filteredIcons" :key="icon" class="icon-item" :class="{ selected: icon === modelValue }"
                @click="$emit('update:modelValue', icon)">
                <i :class="icon"></i>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useApi } from '../../composables/useApi';

const props = defineProps({
    modelValue: String
});

const search = ref('');

// 使用 useApi 获取图标列表
const { result, loading, error, fetchData } = useApi({
    url: '/transactions/search/icons',
    method: 'GET',
    manual: true,
    transform: res => (res.code === 0 && Array.isArray(res.data) ? res.data : [])
});

onMounted(() => {
    fetchData();
});

const filteredIcons = computed(() => {
    if (!result.value) return [];
    const searchTerm = search.value.trim().toLowerCase();
    if (!searchTerm) return result.value;

    // 使用更准确的匹配方式：优先匹配图标名称中包含搜索词的，再匹配以搜索词开头的
    return result.value.filter(icon =>
        icon.toLowerCase().includes(searchTerm)
    ).sort((a, b) => {
        const aStartsWith = a.toLowerCase().startsWith(searchTerm);
        const bStartsWith = b.toLowerCase().startsWith(searchTerm);

        if (aStartsWith && !bStartsWith) return -1;
        if (!aStartsWith && bStartsWith) return 1;
        return a.localeCompare(b);
    });
});
</script>

<style scoped>
.icon-grid {
    display: grid;
    /* 进一步减小最小宽度 */
    grid-template-columns: repeat(auto-fill, minmax(25px, 1fr));
    /* 进一步减小间距 */
    gap: 2px;
    max-height: 200px;
    overflow-y: auto;
    /* 减小右内边距 */
    padding-right: 1px;
}

.icon-grid::-webkit-scrollbar {
    width: 4px;
}

.icon-grid::-webkit-scrollbar-thumb {
    background-color: var(--bs-secondary-color);
    border-radius: 3px;
}

.icon-item {
    text-align: center;
    /* 进一步减小内边距 */
    padding: 2px;
    border: 1px solid transparent;
    /* 进一步减小圆角 */
    border-radius: 2px;
    cursor: pointer;
    transition: 0.2s ease;
    /* 进一步减小字体大小 */
    font-size: 1rem;
    color: var(--bs-body-color);
}

.icon-item:hover {
    background-color: var(--bs-secondary-bg);
}

.icon-item.selected {
    border-color: var(--bs-primary);
    background-color: var(--bs-primary-bg-subtle);
    color: var(--bs-primary);
}
</style>